package com.luyou;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 预编译sql
 */
public class PreparedStatementTest {

    private String driver;
    private String url;
    private String user;
    private String pass;

    public void initParam(String paramFile) throws Exception
    {
        // 使用Properties类来加载属性文件
        Properties props = new Properties();
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(paramFile);
        props.load(is);
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        user = props.getProperty("user");
        pass = props.getProperty("pass");
    }

    public void insertUseStatement() throws SQLException {
        long start = System.currentTimeMillis();
        try (
            Connection conn = DriverManager.getConnection(url, user, pass);
            Statement stmt = conn.createStatement()
        ){
            for (int i = 0; i < 100; i++) {
                stmt.executeUpdate("INSERT INTO student_table VALUES ( null ,'姓名" + i +"')" );
            }
            System.out.println("使用statement费时:" + (System.currentTimeMillis() - start));
        }
    }

    private void insertUsePrepare() throws SQLException {
        long start = System.currentTimeMillis();
        try (
                Connection conn = DriverManager.getConnection(url, user, pass);
                PreparedStatement pstmt = conn.prepareStatement("INSERT INTO student_table VALUES ( null , ?)")
        ){
            for (int i = 0; i <100; i++) {
                pstmt.setString(1, "姓名"+i);
                pstmt.executeUpdate();
            }
            System.out.println("使用PreparedStatement费时:" + (System.currentTimeMillis() - start));
        }
    }

    public static void main(String[] args) throws Exception {
        PreparedStatementTest preparedStatementTest = new PreparedStatementTest();
        preparedStatementTest.initParam("mysql.ini");
        preparedStatementTest.insertUseStatement();
        preparedStatementTest.insertUsePrepare();
    }
}
